package intranet.client;


import java.util.Date;


import java.util.HashMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

import com.google.gwt.user.datepicker.client.DatePicker;

/**
 * @author AHMIM Ahmed
 *
 */


public class Calendarconsult {

	DatePicker datePicker;
	Label titre;	
	
	VerticalPanel vPanel ;
	HorizontalPanel hPanel;
	protected ListBox liste;
	TextArea message;
	Button datebutton;
	PushButton supprimer;
	DataBaseServiceAsync dataBaseService = GWT.create(DataBaseService.class);
	HashMap<String, String[]> eventMap;
	protected String requet,requet1 ;
	Session session;
	DateTimeFormat fmt;
    int res=0;
    Date date;
	
    /**
     * Cette méthode représente le constructeur de la classe calendarconsult   
     * @param sees la session courante
     * 
     */ 
	Calendarconsult(Session sess)
	{ 
		this.session=sess;
		
		
		
				
				

				vPanel= new VerticalPanel();
				hPanel= new HorizontalPanel();   
				liste=new ListBox();
		       
				titre=new Label("Intitulé:");
				hPanel.add(titre);
				hPanel.add(liste);
				supprimer=new PushButton(new Image("delete.png"));
				supprimer.setSize("20px", "20px");
				hPanel.add(supprimer);
				hPanel.setVisible(false);       

				datePicker = new DatePicker();
				
				
				datebutton = new Button();
				datebutton.setVisible(false);
				addstyletodate2();		
				datePicker.setValue(new Date(), true);
				message = new TextArea();
			    message.setVisible(false);
			   
			    
			    
			    vPanel = new VerticalPanel();
			    vPanel.add(datebutton);	    
			    vPanel.add(datePicker);
			    vPanel.add(hPanel);
			    vPanel.add(message);
				
				
				
			 
	    
	    

//------événement associer au click sur une date de datePicker -------------------------------------
	    
	    datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
		      public void onValueChange(ValueChangeEvent<Date> event) {
		       date = event.getValue();
		     fmt = DateTimeFormat.getFormat("dd/MM/yyyy");
		     String dateString=fmt.format(date);
		     datebutton.setVisible(true);
		     datebutton.setText(dateString);
		     datePicker.setVisible(false);  
		      message.setVisible(true);
		      hPanel.setVisible(true);		      
		      requet ="SELECT event.event_id,event_name,event_content FROM event,teacher_event  where teacher_event.teacher_login='"
		      + session.get("teacher_login")+"' and event.event_id=teacher_event.event_id and event_date='"+Long.toString(DatetoBigint(dateString))+"'";			      		      		      
		      addselectedevent();
		      
		      }
		    });


//-----événment associer au clic sur le botton datebutton--------------------------------
	    
   datebutton.addClickHandler(new ClickHandler()
       { 
	    public void onClick(ClickEvent event)
	    {
refrech2();
	   
        }});
        
     

 //-----événment associer au clic sur le botton supprimer--------------------------------       
  supprimer.addClickHandler(new ClickHandler()
	{
		public void onClick(ClickEvent event)
		{
	        	

	        	dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
	        		@Override
	        		public void onSuccess(HashMap<String, String[]> result) {
	        			
	        			if(liste.getItemCount()>0)
	        			{		        	       	
requet1 ="DELETE FROM teacher_event where event_id='"+Integer.parseInt(result.get("event_id")[liste.getSelectedIndex()])+"' and teacher_login='"
	  + session.get("teacher_login")+"'";
	      
	      dataBaseService.delete(requet1, new AsyncCallback<Integer>()
						{
							public void onSuccess(Integer result)
							{
								if (result>0)
								{
									
									
								    addselectedevent();
								   
								    
								}
							}
							
							public void onFailure(Throwable caught)
							{
								
							}
						});		
	        			}
	        		}
	        		@Override
	        		public void onFailure(Throwable caught) {
	        		res=0;	// TODO Auto-generated method stub	
	        		Window.alert("cassé");
	        		}
	        	});
	      
	   
			} });

        
//----événment associer au séléctionnement d'un item de la liste ---------------------
        
  liste.addChangeHandler( new ChangeHandler()
  {
	  public void onChange(ChangeEvent event)
	  {
		  dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
				@Override
				public void onSuccess(HashMap<String, String[]> result) {	
					if (result.get("event_id").length >0)
					{
									
						
				message.setText(result.get("event_content")[liste.getSelectedIndex()]);
				
					}
							}
							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub	
							Window.alert("cassé");
							}
						});
            }
    }); 
  //--------------------------------------------------------------------------------



  
  onResize();     
	
	   }
	
	
	/**
	 * Cette méthode sert à ajouter tous les événements du jour séléctionné dans la liste   

	 * 
	 */		
		
   
	public void addselectedevent()
	{		
		dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
			@Override
			public void onSuccess(HashMap<String, String[]> result) {

				liste.clear();
				for(int i=0;i<result.get("event_id").length;i++)
				{		
					liste.addItem(result.get("event_name")[i]);
					
				}
				
			      if(liste.getItemCount()==0) {
			    	  message.setText("");			    		
			    	  
			      }
			      else {
			      if (liste.getSelectedIndex()!=-1)
			      {  
			    	  dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
			  			@Override
			  			public void onSuccess(HashMap<String, String[]> result) {	
			  				if (result.get("event_id").length >0)
			  				{
			  								
			  					
			  			message.setText(result.get("event_content")[0]);
			  			
			  				}
			  						}
			  						@Override
			  						public void onFailure(Throwable caught) {
			  							// TODO Auto-generated method stub	
			  						Window.alert("cassé");
			  						}
			  					});
			      }else
			      {
			    	  dataBaseService.select(requet, new AsyncCallback<HashMap<String,String[]>>() {
				  			@Override
				  			public void onSuccess(HashMap<String, String[]> result) {	
				  				if (result.get("event_id").length >0)
				  				{
				  								
				  					
				  			message.setText(result.get("event_content")[liste.getSelectedIndex()]);
				  			
				  				}
				  						}
				  						@Override
				  						public void onFailure(Throwable caught) {
				  							// TODO Auto-generated method stub	
				  						Window.alert("cassé");
				  						}
				  					});  
			      }
			      
			      }
				
			}
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("cassé");
				// TODO Auto-generated method stub				
			}
		});
		
	}

	/**
	 * Cette méthode sert à ajouter un Style différent  pour les dates  d'événements   
	 * 
	 */		
//-----------------------------------------------------------------------------------------------
	
	public void addstyletodate()
	{
		
String	requet2 ="SELECT event_date FROM event,teacher_event  where teacher_event.teacher_login='"
+ session.get("teacher_login")+"' and event.event_id=teacher_event.event_id";			      		      
	
	dataBaseService.select(requet2, new AsyncCallback<HashMap<String,String[]>>() {
		@Override
		public void onSuccess(HashMap<String, String[]> result) {
		
			for(int i=0;i<result.get("event_date").length;i++)
			{ 
	datePicker.addStyleToDates("datePickerDayIsHighlighted",new Date(Long.parseLong(result.get("event_date")[i])));
				
			}	
			datePicker.setValue(new Date(), true);
			 datePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {
			      public void onValueChange(ValueChangeEvent<Date> event) {
			       date = event.getValue();
			     fmt = DateTimeFormat.getFormat("dd/MM/yyyy");
			     String dateString=fmt.format(date);
			     datebutton.setVisible(true);
			     datebutton.setText(dateString);
			     datePicker.setVisible(false);  
			      message.setVisible(true);
			      hPanel.setVisible(true);		      
			      requet ="SELECT event.event_id,event_name,event_content FROM event,teacher_event  where teacher_event.teacher_login='"
			      + session.get("teacher_login")+"' and event.event_id=teacher_event.event_id and event_date='"+Long.toString(DatetoBigint(dateString))+"'";			      		      		      
			      addselectedevent();
			      
			      }
			    });
				datePicker.setVisible(true);
				
		}
		@Override
		public void onFailure(Throwable caught) {
			Window.alert("cassé");
			// TODO Auto-generated method stub				
		}
	});
		
		
		
	}
	
	/**
	 * cette methode sert à transformer une date de format dd/MM/yyyy au BigInteger
	 * @param  datep la date au format  dd/MM/yyyy
	 * @return Long qui represente la date 
	 * 
	 */
		
	public static long DatetoBigint(String datep)
	{
		long longDate=0;
		
		DateTimeFormat formatter ; 
	    Date date1; 
	    formatter =  DateTimeFormat.getFormat("dd/MM/yyyy");
	    try {
			date1 = (Date)formatter.parse(datep);
			 longDate=date1.getTime();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	    
	      return longDate;
	    }

	
	/**
	 *  cette methode sert à transformer un BigInteger à une date au format dd/MM/yyyy
	 * @param datep la date autant que Long
	 * @return String qui represente la date sous format dd/MM/yyyy 
	 * 
	 */		
	public static String BinginttoDate(Long datep)
	{
		
		DateTimeFormat sdf = DateTimeFormat.getFormat("dd/MM/yyyy");
	    Date d = new Date(datep);
	    return sdf.format(d);
		
	}
	/**
	 * Cette méthode sert à rafraichir le calendrier  
	 * @param
	 * @return 
	 * 
	 */	
	
	public  void refrech2()
	{
		datePicker.setVisible(false);
		datePicker=null;
		datePicker = new DatePicker();
		datePicker.setSize(Window.getClientWidth()*2/16+"px",Window.getClientHeight()*2/8+"px");		
		addstyletodate();			
		datePicker.setVisible(false);
		vPanel.add(datePicker);
		hPanel.setVisible(false);
		message.setVisible(false);
		datebutton.setVisible(false);
		

		
		
	}
	
	/**
	 * Cette méthode sert à ajouter un Style différent  pour les dates  d'événements lors de chargement de page  
	 * 
	 */	
	public void addstyletodate2()
	{
		
String	requet2 ="SELECT event_date FROM event,teacher_event  where teacher_event.teacher_login='"
+ session.get("teacher_login")+"' and event.event_id=teacher_event.event_id";			      		      
	
	dataBaseService.select(requet2, new AsyncCallback<HashMap<String,String[]>>() {
		@Override
		public void onSuccess(HashMap<String, String[]> result) {
		
			for(int i=0;i<result.get("event_date").length;i++)
			{ 
	datePicker.addStyleToDates("datePickerDayIsHighlighted",new Date(Long.parseLong(result.get("event_date")[i])));
				
			}				
		}
		@Override
		public void onFailure(Throwable caught) {
			Window.alert("cassé");
			// TODO Auto-generated method stub				
		}
	});
		
		
		
	}
	
	/**
	 * cette méthode sert à redimensionner la taille de la calendarconsult en fonction de la taille de la page
	 * 
	 */	
	
	

	 public void onResize()
		{
	    	datePicker.setSize(Window.getClientWidth()*2/16+"px",Window.getClientHeight()*2/8+"px");
	    	message.setSize(Window.getClientWidth()*2/16+"px",Window.getClientHeight()*2/12+"px");
            liste.setSize(Window.getClientWidth()*2/15-(100)+"px",Window.getClientHeight()*2/40+"px");

		}
	 
		/**
		 * Cette méthode retourne le conteneur de tous les composants de Calendarconsult
		 * @return VerticalPanel qui représente le conteneur de tous les composants de Calendarconsult
		 * 
		 */
	

	
	public VerticalPanel get()
	 {
		 return vPanel;
		 
	 }
}


